//
//  ConfirmViewController.m
//  cherryPicker
//
//  Created by Young Soo Yun on 12. 1. 5..
//  Copyright (c) 2012 Happy. All rights reserved.
//

#import "ConfirmViewController.h"

#import "StringUtils.h"
#import "DateUtil.h"
#import "ControlUtil.h"

@implementation ConfirmViewController

@synthesize _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _labTitle.text = (_isModify)?@"카드 결제 수정":@"카드 결제 입력";
    
    if (_isModify) {
        _unmodifyView.alpha = 0.5f;
        _btnDel.hidden = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
//	START_FUNC();
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardShowEvent:) 
													 name:UIKeyboardDidShowNotification 
												   object:nil];	
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardHideEvent:) 
													 name:UIKeyboardDidHideNotification
												   object:nil];	
	} else {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardShowEvent:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardHideEvent:) 
													 name:UIKeyboardWillHideNotification 
												   object:nil];
	}
}

- (void)viewWillDisappear:(BOOL)animated {
//	START_FUNC();
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    _delegate = nil;
    
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField.text isEqualToString:@"0"]) {
        textField.text = @"";
    }
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""]) {
        textField.text = @"0";
    }
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [textField setText:[StringUtils moneyFormat:newText]];
    return NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - Number Keyboard Done
- (void)addButtonToKeyboard {
    //
    [_delegate ConfimKeyBoard:YES];
    
	// create custom button
	UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
	doneButton.frame = CGRectMake(0, 163, 106, 53);
	doneButton.adjustsImageWhenHighlighted = NO;
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
		[doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
	} else {        
		[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
	}
	[doneButton addTarget:self action:@selector(btnNumberKeyHide:) forControlEvents:UIControlEventTouchUpInside];
	// locate keyboard view
	UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
	UIView* keyboard;
	for(int i=0; i<[tempWindow.subviews count]; i++) {
		keyboard = [tempWindow.subviews objectAtIndex:i];
		// keyboard found, add the button
		if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
			if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
				[keyboard addSubview:doneButton];
		} else {
			if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
				[keyboard addSubview:doneButton];
		}
	}
}

- (void)removeButtonToKeyboard{
    //    
    [_delegate ConfimKeyBoard:NO];
    
	UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
	UIView* keyboard;
	for(int i=0; i<[tempWindow.subviews count]; i++) {
		keyboard = [tempWindow.subviews objectAtIndex:i];
		// keyboard found, add the button
		if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
			if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
				[keyboard removeFromSuperview];
		} else {
			if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
				[keyboard removeFromSuperview];
		}
	}
}

- (void)keyboardShowEvent:(NSNotification *)note {
	// if clause is just an additional precaution, you could also dismiss it
	CLOG(@"####### keyboardShowEvent : %@", [note name]);
    [self addButtonToKeyboard];
}

- (void)keyboardHideEvent:(NSNotification *)note{
	CLOG(@"####### keyboardHideEvent : %@", [note name]);
	[self removeButtonToKeyboard];
}

#pragma mark - IBAction

- (IBAction)onPickerView:(id)sender{
    [_tfPrice resignFirstResponder];
    [_tfDiscount resignFirstResponder];
    
    UIButton* btn = (UIButton*)sender;
    
    switch (btn.tag) {
        case TAG_DATE:
            [_delegate ConfirmPickerView:btn.tag labText:_labDate.text];
            break;
        case TAG_CATEGORY:
            [_delegate ConfirmPickerView:btn.tag labText:_labCategory.text];
            break;            
        default:
            [_delegate ConfirmPickerView:btn.tag labText:@""];
            break;
    }
}

- (IBAction)onOK{
    
    if ([_tfPrice.text isEqualToString:@"0"]) {
        [ControlUtil showAlertCaution:@"" body:@"사용금액을 입력하여 주십시오." delegate:nil];
    }else{
        NSString* strPrice = [StringUtils changeNumToStrWithoutWon:_tfPrice.text];
        NSString* strDisCount = [StringUtils changeNumToStrWithoutWon:_tfDiscount.text];
        
        ReceiptDB* receiptDB = [[ReceiptDB alloc] initWithCode:(_isModify)?_ID:0
                                                      cardName: _labCardName.text
                                                          date:_labDate.text
                                                         price:[strPrice intValue]
                                                      category:_labCategory.text
                                                      discount:[strDisCount intValue]
                                                     delimiter:_strDelimiter
                                                         place:_labPlace.text];
        
        if (_isModify) {
            [CherryPickerDB updateToReceipt:receiptDB];
            [_delegate ConfirmOKClick];
        }else{
            [CherryPickerDB insertFromReceipt:receiptDB];
            [_delegate ConfirmOKClick];            
        }
    }
}

- (IBAction)onCancel{
    [_delegate ConfirmCancelClick];
}

- (IBAction)onDel{
    [CherryPickerDB deleteReceiptWhereID:_ID];
    [_delegate ConfimDelClick];
}

#pragma mark -

- (void)initType:(ConfirmType)type{
    _isModify = (type == MODIFY_RECEIPT)?YES:NO;
}

- (void)initList:(NSString*)cardName
       delimiter:(NSString*)delimiter
       checkDate:(NSString*)checkDate
        strPrice:(NSString*)strPrice{
    _labCardName.text = cardName;
    
    _strDelimiter = [delimiter retain];
    
    NSString* nowDate = [DateUtil nowDateStr];
    
    _labDate.text = [NSString stringWithFormat:@"%@/%@", [nowDate substringToIndex:4], checkDate];
    _tfPrice.text = strPrice;
}

- (void)initData:(ReceiptDB*)receiptDB{
    _ID = receiptDB._Id;
    _labCardName.text = receiptDB._CardName;
    _strDelimiter = [receiptDB._Delimiter retain];
    _labCategory.text = receiptDB._Category;
    _labPlace.text = receiptDB._Place;
    _labDate.text = receiptDB._Date;
    _tfPrice.text = [StringUtils moneyFormat:[NSString stringWithFormat:@"%d", receiptDB._Price]];
    _tfDiscount.text = [StringUtils moneyFormat:[NSString stringWithFormat:@"%d", receiptDB._Discount]];
    
}

- (void)setDate:(NSString*)checkDate{
    _labDate.text = checkDate;
}

- (void)setLabel:(NSString*)labText
             tag:(NSInteger)tag{
    switch (tag) {
        case TAG_CARDNAME:
            _labCardName.text = labText;
            break;
        case TAG_CATEGORY:
            _labCategory.text = labText;
            break;
        case TAG_PLACE:
            _labPlace.text = labText;
            break;
    }
}

- (void)btnNumberKeyHide:(id)sender{
	[_tfPrice resignFirstResponder];
    [_tfDiscount resignFirstResponder];
}

@end
